package com.whl.sm.controller.expense;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.common.util.UploadUtils;
import com.whl.sm.controller.BaseController;
import com.whl.sm.model.assets.ComUnits;
import com.whl.sm.model.expense.ContractTenancy;
import com.whl.sm.model.expense.ExpenseType;
import com.whl.sm.model.expense.MaterRecord;
import com.whl.sm.model.inhabitant.AssetsTenant;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.service.assets.ComUnitsService;
import com.whl.sm.service.expense.ContractTenancyService;
import com.whl.sm.service.expense.ExpenseTypeService;
import com.whl.sm.service.inhabitant.AssetsTenantService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.vo.OrgUserContractTenancyExpenseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2021-10-25
 */
@RestController
@RequestMapping("/contract-tenancy")
@Slf4j
public class ContractTenancyController extends BaseController {

    @Autowired
    private ContractTenancyService contractTenancyService;

    @Autowired
    private AssetsTenantService assetsTenantService;

    @Autowired
    private ComUnitsService comUnitsService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private ExpenseTypeService expenseTypeService;

    @Value("${ROOT_PATH}")
    private String rootPath;

    @RequestMapping("/list")
    public Result getComList(HttpServletRequest request){
        QueryWrapper queryWrapper = new QueryWrapper();
        setHttpRequestQueryWrapper(queryWrapper,"visible");
        String unit_id = request.getParameter("unit_id");
        if ( unit_id!=null && !unit_id.equals("undefined") && !unit_id.equals("")) {
            List<AssetsTenant> tenantList = assetsTenantService.list(new QueryWrapper<AssetsTenant>()
                    .eq("assets_id",unit_id)
            );
            List<String> idList = new ArrayList<>();
            if (tenantList.size()>0){
                idList = tenantList.stream().map(AssetsTenant::getId).collect(Collectors.toList());
                queryWrapper.in("tenant_id",idList);
            }

        }
        queryWrapper.ne("is_del",1);
        queryWrapper.orderByDesc("update_time");
        Page<Object> contractPage = contractTenancyService.page(getPage(),queryWrapper);
        List<Object> resultPage = contractPage.getRecords().stream().map(obj->{
            ContractTenancy contractTenancy = (ContractTenancy) obj;
            AssetsTenant assetsTenant = assetsTenantService.getById(contractTenancy.getTenantId());
            ComUnits comUnits = comUnitsService.getById(assetsTenant.getAssetsId());
            OrgUserInfo orgUserInfo = orgUserInfoService.getOne(new QueryWrapper<OrgUserInfo>()
                    .eq("user_id",assetsTenant.getUserId())
            );
            ExpenseType expenseType = expenseTypeService.getById(contractTenancy.getExpenseId());

            return new OrgUserContractTenancyExpenseVo(contractTenancy,comUnits,orgUserInfo,expenseType);
        }).collect(Collectors.toList());
        contractPage.setRecords(resultPage);
        return Result.ok(contractPage);
    }


    @RequestMapping("/info/{id}")
    public Result contractTenancyInfo(@PathVariable("id") String id){
        ContractTenancy contractTenancy = contractTenancyService.getById(id);
        return Result.ok(contractTenancy);
    }


    @RequestMapping("/update")
    public Result update(@RequestBody ContractTenancy contractTenancy ){
        return contractTenancyService.update(contractTenancy);

    }

    @RequestMapping("/buildBill")
    public Result batchBuildBill(@RequestBody List<String> idList){
        return contractTenancyService.addBill(idList);
    }

    @RequestMapping("/logDelete")
    public Result logicalDelete(@RequestBody List<String> idList){
        for (int i = 0; i <idList.size() ; i++) {
            contractTenancyService.update(new UpdateWrapper<ContractTenancy>()
                    .eq("id",idList.get(i))
                    .set("is_del",1)
            );
        }
        return Result.ok();
    }


    @RequestMapping("/uploadFile")
    public Result upload(@RequestParam MultipartFile conPro,@RequestParam("id") String id,HttpServletRequest request){
        String path = "/assets/contractTenancy";
        try {
            List<Map<String,Object>> fileList = UploadUtils.saveFile(request,path,this.rootPath,"conPro");
            String resultPath = "";
            if (fileList.size()>0){
                for (Map<String,Object> map : fileList){
                    resultPath = (String) map.get("filePath");
                }
            }
            ContractTenancy targetTenancy = contractTenancyService.getById(id);
            targetTenancy.setContractUrl(resultPath);
            contractTenancyService.update(targetTenancy);
        }catch (Exception e){
            log.error("费用管理----->租赁合同:上传合同扫描文件失败!");
            return Result.fail();
        }
        return Result.ok();
    }





}
